﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kinect.Toolbox.Collectors;
using Microsoft.Kinect;
using Microsoft.Practices.Unity;

namespace Kinect.Toolbox.Providers
{
    public class KinectFrameProvider : IFrameProvider
    {
        private KinectSensor _kinectSensor;
        public event EventHandler<FrameReadyEventArgs> FrameReady;

        public KinectFrameProvider()
        {
            DependencyFactory.Container.Resolve<IKinectEvents>().KinectInitialized += OnKinectInitialized;
            DependencyFactory.Container.Resolve<IKinectEvents>().KinectUninitializing += OnKinectUninitializing;
        }

        private void OnSkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs args)
        {
            using (var skeletonFrame = args.OpenSkeletonFrame())
            {
                if (skeletonFrame == null)
                    return;

                var frame = new Frame(skeletonFrame);

                if (FrameReady != null)
                {
                    FrameReady(sender, new FrameReadyEventArgs(frame));
                }

            }
        }

        private void OnKinectUninitializing(object sender, EventArgs eventArgs)
        {
            if (_kinectSensor != null)
            {
                _kinectSensor.SkeletonFrameReady -= OnSkeletonFrameReady;
            } 
        }

        private void OnKinectInitialized(object sender, EventArgs eventArgs)
        {
            _kinectSensor = DependencyFactory.Container.Resolve<KinectSensor>();
            _kinectSensor.SkeletonFrameReady += OnSkeletonFrameReady;
        }
    }
}
